#!/usr/bin/python
#coding=utf-8
'''
xrdplot by spacexi
version 0.9
'''
import numpy as np
import matplotlib.pyplot as plt
import re
import os
def loadData(flieName):  #用来去读文件同时将读取到的文件赋值给x和y并转化为float值

	inFile = open(flieName, 'r')  
	x = []
	y = []
	for line in inFile:  
		trainingSet = re.split('\\s+|,|\n',line) #用来从txt中逐行拆分字符串

		if trainingSet[1]!='':
			x.append(trainingSet[0])
			y.append(trainingSet[1])
	x=Tofloat(x)
	y=Tofloat(y)
	return (x, y)

def list_txt_file(file_dir):
	file_list=[]
	label_list=[]
	for root, dirs, files in os.walk(file_dir):
		for file in files:
			if os.path.splitext(file)[1] == '.txt':
				file_list.append(file)
				name_parted=re.split('-',file)
				label_list.append(name_parted[1][0:-4])
	return (file_list,label_list)

def Tofloat(x):# 转化为float数值
	for j in range(len(x)):
			x[j]=float(x[j])
	return x
	
def addy(y,number_of_data):#用于绘制多个曲线时逐个偏移y值来错开曲线
	for i in range(len(y)):
		y[i]+=number_of_data*add_y_value
	return y
	
def xrd_color(color_number):#用来设定不同曲线的颜色，超过8个图谱之后颜色会有相同
	if color_number>=8: color_number=colornumber%8
	color_list=['black','blue','green','red','m','olive','coral','crimson']
	return color_list[color_number]	

def xrd_plot(local_file,local_label):#用来绘图，y轴最大值由所有图谱的最大y值来判断

	Max_y_value=0
	for i in range(len(local_file)):
		(x,y) = loadData(local_file[i])
		y=addy(y,i)
		plt.plot(x, y, color=xrd_color(i),linewidth=1,label=local_label[i])
		if max(y)>Max_y_value:
			Max_y_value=max(y)
	return Max_y_value	

add_y_value=1000
# 此处设置y方向的偏移量

(local_file,local_label)=list_txt_file(os.getcwd())
# 读取当前目录的所有txt文件名，同时转化成图例

ax = plt.subplot(111) 
ymax=xrd_plot(local_file,local_label)
plt.xlabel('2-Theta')  
plt.ylabel('Intensity')
plt.yticks([])
plt.xlim(30,70)
# 此处设置2-Theta的范围

plt.ylim(0,ymax*1.1//1000*1000)
ax.tick_params(direction='in')
#ax.set_title('XRD Result')
# 此处设置图题

plt.legend(loc="upper right",edgecolor='none')
# 此处设置图例位置
plt.show()
